package com.ali.config;

import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * 自定义断言
 */
@Slf4j
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {
    public static final String KEY = "type";

    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(KEY);
    }

    /**
     * 校验规则
     */
    public Predicate<ServerWebExchange> apply(final Config config) {
        return (GatewayPredicate) serverWebExchange -> {
            String type = serverWebExchange.getRequest().getQueryParams().getFirst(KEY);
            log.info("进入自定义断言，断言type：" + config.getType() + "，传值type:" + type);
            return Objects.equals(config.getType(), type);
        };
    }

    @Data
    @Validated
    public static class Config {
        @NotNull
        private String type;
    }
}
